package com.mysen.sso.thirdclient;

import static com.mysen.thirdclient.wx.WxConstant.APPID;
import static com.mysen.thirdclient.wx.WxConstant.GRANT_TYPE;
import static com.mysen.thirdclient.wx.WxConstant.JSCODE2SESSIONAPI;
import static com.mysen.thirdclient.wx.WxConstant.MSG_JSCODE_ERROR;
import static com.mysen.thirdclient.wx.WxConstant.SECRET;

import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysen.exception.MaikeServiceException;
import com.mysen.model.Response;
import com.mysen.thirdclient.wx.WxClientService;
import com.mysen.util.HttpClientHelper;
import com.mysen.util.HttpClientHelper.HttpResponse;

@Component
public class WxLoginService extends WxClientService {

	private static final Logger LOGGER = LoggerFactory.getLogger(WxLoginService.class);
	
    /**
	 * 登陆 获取 openId
	 * */
	public JSONObject login(String jscode) throws Exception {
		String api = String.format(JSCODE2SESSIONAPI, APPID, SECRET, jscode, GRANT_TYPE);
		HttpClientHelper client = HttpClientHelper.getHttpClient();
		HttpResponse response = client.execute(new HttpGet(api));
		if(response.getStatus()/100 == 2) {
			JSONObject object = JSON.parseObject(response.getContent());
			if(object.containsKey("session_key") && object.containsKey("openid")) {
				return object;
			}else{
				LOGGER.error("loginWx jscode error! url:{} resp:{}", api, object);
				throw new MaikeServiceException(MSG_JSCODE_ERROR);
			}
		} else {
			LOGGER.error("loginWx error response code error!");
			throw new MaikeServiceException(Response.MSG_SERVICE_ERROR);
		}
	}
}
